﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text.RegularExpressions;

namespace MailRuWrapper
{
    internal static class InternalHelper
    {
        public static string ToRequestParam(this int[] source, string paramName)
        {
            if (source == null) return "";

            return source.Length > 0
                       ?
                           paramName + "=" + source.Aggregate("", (current, next) => current + "," + next)
                       :
                           "";
        }

        public static string ToRequestParam(this int source, string paramName)
        {
            return source > 0 ? paramName + "=" + source : "";
        }

        public static string ToRequestParam(this string[] source, string paramName)
        {
            if (source == null) return "";

            return source.Length > 0
                       ?
                           paramName + "=" + source.Aggregate((current, next) => current + "," + next)
                       :
                           "";
        }

        public static string ToRequestParam(this string source, string paramName)
        {
            if (string.IsNullOrEmpty(source)) return "";
            return paramName + "=" + source;
        }

        public static string Escape(this string source)
        {
            return source.Replace("&", "%26").Replace("#", "%23");
        }

        public static string ToRequestParam(this bool source, string paramName)
        {
            return paramName + "=" + (source ? "1" : "0");
        }

        public static string ToRequestParam(this Enum source, string paramName)
        {
            return paramName + "=" + (source.GetAttributes<DefaultValueAttribute>().Single().Value as string);
        }

        public static IEnumerable<string> Sort(this IEnumerable<string> source)
        {
            var _l = new List<string>(source);
            _l.Sort();
            return _l;
        }

        public static IEnumerable<T> GetAttributes<T>(this Enum value) where T : Attribute
        {
            if (value != null)
            {
                var _at = (T[])value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof(T), true);
                return _at;
            }
            return null;
        }

        public static string GetExceptionLog(this Exception source)
        {
            var _result = source.Message + Environment.NewLine + source.StackTrace + Environment.NewLine;

            while (source.InnerException != null)
            {
                source = source.InnerException;
                _result += source.Message + Environment.NewLine + source.StackTrace + Environment.NewLine;
            }
            return _result;
        }

        public static string MailAddress(this IUser source)
        {
            if (source.Link != null && source.Link.AbsoluteUri != "")
            {
                var _regEx = new Regex(@"/([^/]+?)/([^/]+?)/$");
                if (_regEx.IsMatch(source.Link.AbsoluteUri))
                {
                    var _m = _regEx.Match(source.Link.AbsoluteUri);
                    return _m.Groups[2] + "@" + _m.Groups[1] + ".ru";
                }
                return "";
            }
            return "";
        }

        /// <summary>
        /// Ссылка на gif изображение статуса Mail.Ru Агент пользователя
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static string StatusAgent(this IUser source)
        {
            return "http://status.mail.ru/?" + source.MailAddress();
        }


        public static RefererTypes ToRefererType(this string source)
        {
            switch (source)
            {
                case "stream.install":
                    return RefererTypes.StreamInstall;
                case "stream.publish":
                    return RefererTypes.StreamPublish;
                case "invitation":
                    return RefererTypes.Invitation;
                case "installed_apps":
                    return RefererTypes.InstalledApps;
                case "catalog":
                    return RefererTypes.Catalog;
                case "mailru_featured":
                    return RefererTypes.MailruFeatured;
                default:
                    return RefererTypes.None;
            }
        }

        public static bool IsReferred(this RefererTypes source)
        {
            switch (source)
            {
                case RefererTypes.None:
                    return false;
                case RefererTypes.StreamInstall:
                    return true;
                case RefererTypes.StreamPublish:
                    return true;
                case RefererTypes.Invitation:
                    return true;
                case RefererTypes.InstalledApps:
                    return true;
                case RefererTypes.Catalog:
                    return false;
                case RefererTypes.MailruFeatured:
                    return false;
                default:
                    throw new ArgumentOutOfRangeException("source");
            }
        }
    }

    public static partial class Helper
    {
        ///<summary>
        /// Позволяет обернуть обычный Exception в Fault исключение
        ///</summary>
        ///<param name="source"></param>
        ///<returns></returns>
        public static FaultMailRuWrapperException ToFault(this Exception source)
        {
            return new FaultMailRuWrapperException { Message = source.Message };
        }

        ///<summary>
        /// Позволяет обернуть обычный <see cref="MailRuWrapperRequestException"/> в Fault исключение
        ///</summary>
        ///<param name="source"></param>
        ///<returns></returns>
        public static FaultMailRuWrapperRequestException ToFault(this MailRuWrapperRequestException source)
        {
            return new FaultMailRuWrapperRequestException { Message = source.Message, Code = source.Code, Request = source.Request };
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="item"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public static bool HasFlag(this LogLevel item, LogLevel query)
        {
            return ((item & query) == query);
        }
    }

}
